<template>
  <div ref="boxwrap" class="paramset-wrap mt-50">
    <div ref="filterwrap" class="filter-container">
      <el-form ref="form" :inline="true" :model="form" size="small">
        <el-form-item label="制程">
          <el-tooltip class="item" effect="dark" content="可多选" placement="top">
            <el-select v-model="form.regionid" placeholder="请选择" class="filter-item" filterable multiple collapse-tags @change="LoadLines()">
              <el-option v-for="item in form.regionArr" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="线别">
          <el-tooltip class="item" effect="dark" content="可多选" placement="top">
            <el-select v-model="form.lineId" placeholder="请选择" class="filter-item" filterable multiple collapse-tags @change="LoadSlots()">
              <el-option v-for="item in form.lineArr" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="槽/段">
          <el-tooltip class="item" effect="dark" content="可多选" placement="top">
            <el-select v-model="form.slotId" placeholder="请选择" class="filter-item" filterable multiple collapse-tags @change="LoadDevices()">
              <el-option v-for="item in form.slotArr" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="仪表类型">
          <el-tooltip class="item" effect="dark" content="可多选" placement="top">
            <el-select v-model="form.devType" placeholder="请选择" class="filter-item" filterable multiple collapse-tags @change="filterDeviceByType">
              <el-option v-for="item in deviceTypeList" :key="item.typeId" :label="item.typeName" :value="item.typeId" />
            </el-select>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="仪表">
          <el-tooltip class="item" effect="dark" content="可多选" placement="top">
            <el-select v-model="form.devId" placeholder="请选择" class="filter-item" filterable multiple collapse-tags>
              <el-option v-for="item in form.devArr" :key="item.devId" :label="item.devName" :value="item.devId" />
            </el-select>
          </el-tooltip>
        </el-form-item>
        <!-- <el-button class="filter-item" type="primary" icon="el-icon-search" size="small" @click="handleSearch()">查询</el-button> -->
      </el-form>
    </div>
    <div class="table-main">
      <div class="table-list">
        <el-table
          :key="tableKey"
          v-loading="listLoading"
          element-loading-text="Loading"
          :data="pageList"
          border
          fit
          style="width: 100%;"
          size="small"
          :height="tableHeight"
          :max-height="tableHeight"
          @current-change="handleSelection"
        >
          <el-table-column label="" align="center" width="60" fixed="left" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-radio v-model="currentChecked" :label="scope.row.checked"><span /></el-radio>
            </template>
          </el-table-column>
          <el-table-column label="序号" align="center" type="index" width="80" :index="indexMethod" />
          <el-table-column v-for="(item, index) in tableCol" :key="index" :label="item.label" align="center" :width="item.width || ''">
            <template slot-scope="scope">{{ scope.row[item.prop] }}</template>
          </el-table-column>
        </el-table>

        <pagination :total="pageObj.total" :page-sizes="pageObj.pageSize" :page.sync="pageObj.page" :limit.sync="pageObj.limit" layout="total, sizes, prev, pager, next" @pagination="getPage" />
      </div>

      <div class="operate-btns">
        <el-button class="" type="primary" plain icon="el-icon-search" @click="handleSearch()">查询</el-button>
        <el-button class="" type="primary" plain icon="el-icon-edit" @click="handleUpdate()">编辑</el-button>
      </div>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form ref="dataForm" :model="temp" label-position="left" label-width="90px" class="dialog-form" :rules="rules">
        <el-form-item label="制程">
          <el-input v-model="temp.regionName" :disabled="true" />
        </el-form-item>
        <el-form-item label="线别">
          <el-input v-model="temp.lineName" :disabled="true" />
        </el-form-item>
        <el-form-item label="槽/段">
          <el-input v-model="temp.slotName" :disabled="true" />
        </el-form-item>
        <el-form-item label="仪表">
          <el-input v-model="temp.devName" :disabled="true" />
        </el-form-item>
        <el-form-item label="上限" prop="upperLimit">
          <el-input v-model="temp.upperLimit" type="number" step="0.1" />
        </el-form-item>
        <el-form-item label="下限" prop="lowerLimit">
          <el-input v-model="temp.lowerLimit" type="number" step="0.1" />
        </el-form-item>
        <el-form-item label="PLC名称" prop="imId">
          <el-select v-model="temp.imId" placeholder="请选择" class="filter-item">
            <el-option v-for="item in plcList" :key="item.plcId" :label="item.plcName" :value="item.plcId" />
          </el-select>
        </el-form-item>
        <el-form-item label="PLC点位" prop="stackAddr">
          <el-input v-model="temp.stackAddr" type="number" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" size="small" @click="updateData('dataForm')">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { defaultDevType } from '@/api/default-apis'
import { getProcess, getLineByProcess, getSlotByLine, getDeviceBySlot } from '@/api/conf'
import { getDeviceAll, updateDevice, getPlc } from '@/api/reports'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { isValued, idsStr } from '@/utils'
export default {
  name: 'ParamSetting',
  components: { Pagination },
  data() {
    // 验证：上限 >下限 >= 0
    var validatorUpper = (rule, value, callback) => {
      const val = parseFloat(value)
      if (value === '') {
        return callback('上限不能为空')
      } else if (val <= 0) {
        return callback('请输非负数字')
      } else if (val < this.temp.lowerLimit) {
        return callback('上限需高于下限')
      } else {
        return callback()
      }
    }
    var validatorLower = (rule, value, callback) => {
      const val = parseFloat(value)
      if (value === '') {
        return callback('下限不能为空')
      } else if (val < 0) {
        return callback('请输非负数字')
      } else if (val > this.temp.upperLimit) {
        return callback('下限需低于上限')
      } else {
        return callback()
      }
    }
    return {
      tableKey: 0,
      list: [],
      pageList: [],
      listLoading: false,
      deviceTypeList: [],
      deviceTypeObj: {},
      tableCol: [
        { label: '制程', prop: 'regionName' },
        { label: '线别', prop: 'lineName' },
        { label: '槽/段', prop: 'slotName' },
        { label: '仪表类型', prop: 'devTypeStr', width: '100' },
        { label: '仪表名称', prop: 'devName' },
        { label: '上限', prop: 'upperLimit', width: '100' },
        { label: '下限', prop: 'lowerLimit', width: '100' },
        { label: '单位', prop: 'devUnit', width: '100' },
        { label: 'PLC名称', prop: 'plcName' },
        { label: 'PLC点位', prop: 'stackAddr' }
      ],
      tableHeight: 'auto',
      form: {
        regionid: [],
        regionArr: [],
        lineId: [],
        lineArr: [],
        slotId: [],
        slotArr: [],
        devType: [],
        devId: [],
        devArr: []
      },
      deviceList: [],
      listQuery: {
        regionids: '',
        lineIds: '',
        slotIds: '',
        devTypes: '',
        devIds: ''
      },
      lineQuery: {
        regionid: ''
      },
      soltQuery: {
        lineId: ''
      },
      devQuery: {
        slotId: ''
      },
      devTypes: '',
      pageObj: {
        page: 1, // 第几页
        limit: 20, // 每页条数
        total: 0, // 总条数
        pageSize: [20, 40, 60, 80, 100]
      },
      temp: {
        regionName: '',
        lineName: '',
        slotName: '',
        devName: '',
        upperLimit: '',
        lowerLimit: '',
        stackAddr: '',
        imId: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        upperLimit: [
          { required: true, validator: validatorUpper, trigger: 'blur' }
        ],
        lowerLimit: [
          { required: true, validator: validatorLower, trigger: 'blur' }
        ],
        imId: [{ required: true, trigger: 'blur' }],
        stackAddr: [{ required: true, trigger: 'blur' }]
      },
      plcList: [],
      plcObj: {},
      currentChecked: '',
      currentSelectItem: null // 选中的行
    }
  },
  watch: {
    // 监听 lineId、slotId变化，清空关联的input值
    // 'form.lineId': function(newValue, oldValue) {
    //   this.form.slotId = null
    // },
    // 'form.slotId': function(newValue, oldValue) {
    //   this.form.devId = null
    // }
  },
  mounted() {
    this.getTableHeight()
  },
  created() {
    this.init()
    this.getPlcData()
  },
  methods: {
    init() {
      defaultDevType().then(res => {
        this.deviceTypeList = [].concat(res)
        this.deviceTypeList.forEach(val => {
          this.deviceTypeObj[val.typeId] = val.typeName
        })
      })
      getProcess().then(res => {
        this.form.regionArr = res.data
        this.LoadLines()
      })
    },
    LoadLines() {
      if (isValued(this.form.regionid)) {
        this.lineQuery.regionid = idsStr(this.form.regionid, 'id', true)
      } else {
        this.lineQuery.regionid = idsStr(this.form.regionArr, 'id', false)
      }
      getLineByProcess(this.lineQuery).then(res => {
        this.form.lineArr = res.data
        this.LoadSlots()
      })
    },
    LoadSlots() {
      if (isValued(this.form.lineId)) {
        this.soltQuery.lineId = idsStr(this.form.lineId, 'id', true)
      } else {
        this.soltQuery.lineId = idsStr(this.form.lineArr, 'id', false)
      }
      getSlotByLine(this.soltQuery).then(res => {
        this.form.slotArr = res.data
        this.LoadDevices()
      })
    },
    LoadDevices() {
      if (isValued(this.form.slotId)) {
        this.devQuery.slotId = idsStr(this.form.slotId, 'id', true)
      } else {
        this.devQuery.slotId = idsStr(this.form.slotArr, 'id', false)
      }
      const query = Object.assign({}, this.lineQuery, this.soltQuery, this.devQuery)
      getDeviceBySlot(query).then(res => {
        this.deviceList = res.data
        this.filterDeviceByType()
      })
    },
    filterDeviceByType() {
      this.form.devArr = []
      if (isValued(this.form.devType)) {
        this.devTypes = this.form.devType.join(',')
        this.deviceList.forEach(item => {
          this.form.devType.forEach(val => {
            if (item.devType === parseInt(val)) {
              this.form.devArr.push(item)
            }
          })
        })
      } else {
        this.devTypes = Object.keys(this.deviceTypeObj).join(',')
        this.form.devArr = this.deviceList
      }
      this.handleSearch()
    },
    getPlcData() {
      getPlc().then(res => {
        this.plcList = res.data
        this.plcList.forEach(val => {
          this.plcObj[val.plcId] = val.plcName
        })
      })
    },
    // 查询
    handleSearch() {
      this.listLoading = true
      let devids = ''
      if (isValued(this.form.devId)) {
        devids = idsStr(this.form.devId, 'devId', true)
      } else {
        devids = idsStr(this.form.devArr, 'devId', false)
      }
      this.listQuery = {
        regionids: this.lineQuery.regionid,
        lineIds: this.soltQuery.lineId,
        slotIds: this.devQuery.slotId,
        devTypes: this.devTypes,
        devIds: devids
      }
      getDeviceAll(this.listQuery).then(res => {
        res.data.forEach(item => {
          item.devTypeStr = this.deviceTypeObj[item.devType]
          item.checked = item.devId
        })
        this.list = res.data
        this.pageObj.total = res.data.length
        this.getPage()
        this.listLoading = false
      }).catch(() => {
        this.listLoading = false
      })
    },
    getPage() {
      this.pageList = this.list.filter((item, index) => {
        return index < this.pageObj.limit * this.pageObj.page && index >= this.pageObj.limit * (this.pageObj.page - 1)
      })
    },
    indexMethod(index) { // 表格序号方法,翻页后序号连续
      return (index + 1) + (this.pageObj.page - 1) * this.pageObj.limit
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    // 选中行
    handleSelection(currentRow) {
      if (currentRow) {
        this.currentChecked = currentRow.devId
        this.currentSelectItem = Object.assign({}, currentRow)
        this.currentSelectItem.checked = this.currentSelectItem.devId
      }
      // console.log(currentRow)
    },
    handleUpdate() {
      if (this.currentSelectItem) {
        this.temp = Object.assign({}, this.currentSelectItem) // copy obj
        this.temp.imId = this.temp.imId === 0 ? '' : this.temp.imId

        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      } else {
        this.$message({
          message: '请选择一条数据',
          type: 'warning'
        })
      }
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.plcName = this.temp.imId === 0 ? '' : this.plcObj[this.temp.imId]
          const tempData = Object.assign({}, this.temp)
          updateDevice(tempData).then(res => {
            let msgType = 'error'
            if (res.code === '000000') {
              msgType = 'success'
              for (const v of this.list) {
                if (v.devId === tempData.devId) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, tempData)
                  this.getPage()
                  break
                }
              }
            }
            this.$message({
              message: msgType,
              type: msgType,
              duration: 2000
            })
          }).then(() => {
            this.dialogFormVisible = false
          })
        }
      })
    },
    handleDelete(row) {
      this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000
      })
      const index = this.list.indexOf(row)
      this.list.splice(index, 1)
      this.getPage()
    },
    getTableHeight() {
      const that = this
      const dom = this.$refs.boxwrap
      const filterwrap = this.$refs.filterwrap
      this.$erd.listenTo(dom, function(element) {
        that.tableHeight = dom.clientHeight - filterwrap.clientHeight - 50
      })
    }
  }
}
</script>
<style lang="scss" scoped>
  .paramset-wrap{
    height: calc(100% - 50px);
  }
  .dialog-form{
    width: 90%;
    margin:0 auto;
  }
  .el-table{
    width: 100%;
    touch-action:none;
  }
  .el-form-item--small.el-form-item{
    margin-bottom: 5px;
  }
</style>
